//
//  BrowserViewCtr.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/6/21.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit
import SDWebImage

class BrowserViewCtr: UIViewController {

    var bmiddle_pic: [URL]

    var indexPath: IndexPath
    
    var selectedIndexPath: IndexPath?
    
    var cellDic: [String: String]
    

    init(bmiddle_pic: [URL], indexPath: IndexPath) {
        self.bmiddle_pic = bmiddle_pic
        self.indexPath = indexPath
        self.cellDic = [String: String]()

        super.init(nibName: nil, bundle: nil)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
    }
    
    // MARK: - 内部控制方法
    private func setupUI(){
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[collectionView]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView])
        view.addConstraints(cons)
        
        closeBtn.translatesAutoresizingMaskIntoConstraints = false
        saveBtn.translatesAutoresizingMaskIntoConstraints = false
        let dict = ["closeBtn": closeBtn, "saveBtn": saveBtn]
        let closeHCons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[closeBtn(100)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: dict)
        let closeVCons = NSLayoutConstraint.constraints(withVisualFormat: "V:[closeBtn(50)]-20-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: dict)
        view.addConstraints(closeHCons)
        view.addConstraints(closeVCons)
        
        let saveHCons = NSLayoutConstraint.constraints(withVisualFormat: "H:[saveBtn(100)]-20-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: dict)
        let saveVCons = NSLayoutConstraint.constraints(withVisualFormat: "V:[saveBtn(50)]-20-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: dict)
        view.addConstraints(saveHCons)
        view.addConstraints(saveVCons)
    }
    
    @objc private func closeBtnClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func saveBtnClick(){
        
    }
    
    // MARK: - 懒加载
    private lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: .zero, collectionViewLayout: ZXJBrowserLayout())
        clv.delegate = self
        clv.dataSource = self
        if #available(iOS 10.0, *) {
            clv.isPrefetchingEnabled = false
        } else {
            // Fallback on earlier versions
        }
        clv.register(ZXJBroserCell.self, forCellWithReuseIdentifier: "browserCell")

        return clv
    }()
    
    private lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("关闭", for: .normal)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside)
        return btn
    }()
    
    private lazy var saveBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", for: .normal)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
        return btn
    }()
}

extension BrowserViewCtr: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bmiddle_pic.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
//        dict["height"] = 1.88 as AnyObject

        //保留缩放后的图片
//        var identifier = cellDic["\(indexPath)"]
//        if identifier == nil {
//            identifier = "\(indexPath)"
//            cellDic["\(indexPath)"] = identifier
//            collectionView.register(ZXJBroserCell.self, forCellWithReuseIdentifier: identifier!)
//        }
        
//        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier!, for: indexPath) as! ZXJBroserCell

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "browserCell", for: indexPath) as! ZXJBroserCell

        cell.imageUrl = bmiddle_pic[indexPath.item]
//        selectedIndexPath = indexPath;
        NSLog(message: "item = \(indexPath.item)")

        return cell
    }
//
//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        NSLog(message: "a a a a a a a ")
//    }
    
//    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
//        NSLog(message: "滚！！！！！！！！！！1")
//        //        guard let index = selected else { return <#return value#> }
//    }
    
    
}

class ZXJBroserCell: UICollectionViewCell, UIScrollViewDelegate {
        
    var imageUrl: URL?{
        didSet{
            
            resetView()
            
            imageView.sd_setImage(with: imageUrl) { (image, error, _, _) in
//                self.imageView.sizeToFit()
                let width = UIScreen.main.bounds.width
                let height = UIScreen.main.bounds.height

                //计算图片宽高比
                let scale = image!.size.height / image!.size.width
                //等比缩放图片
                let imageHeight = scale * width
                
                self.imageView.frame = CGRect(origin: .zero, size: CGSize(width: width, height: imageHeight))
                
                if imageHeight < height {
                    
                    let offsetY = (height - imageHeight) * 0.5
                    self.scrollView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
                }else{
                    self.scrollView.contentSize = CGSize(width: width, height: imageHeight)
                }
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func resetView(){
        scrollView.contentSize = CGSize.zero
        scrollView.contentInset = UIEdgeInsets.zero
        scrollView.contentOffset = CGPoint.zero
        
        imageView.transform = CGAffineTransform.identity
    }
    
    private func setupUI(){
//        contentView.addSubview(imageView)

        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        
        scrollView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: UIScreen.main.bounds.size) //self.frame
    }
    
    private lazy var scrollView: UIScrollView = {
        let sc = UIScrollView()
        sc.maximumZoomScale = 2.0
        sc.minimumZoomScale = 0.5
        sc.delegate = self
        
        return sc
    }()
    
    private lazy var imageView = UIImageView()
    
    // MARK: - UIScrollViewDelegate
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {

        var offsetY = (k_Screen_Height - imageView.frame.height) * 0.5
        var offsetX = (k_Screen_Width - imageView.frame.width) * 0.5
        NSLog(message: "offsetY = \(offsetY), offsetX = \(offsetX) ")
        offsetY = (offsetY < 0) ? 0 : offsetY
        offsetX = (offsetX < 0) ? 0 : offsetX

        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX)
    }
    
}


extension BrowserViewCtr: UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        selectedIndexPath = indexPath;
        
//        let newCell = cell as! ZXJBroserCell
//        newCell.resetView()
//        let cell = collectionView.cellForItem(at: indexPath) as? ZXJBroserCell
//        cell?.resetView()
    }
    

}

class ZXJBrowserLayout: UICollectionViewFlowLayout{
    override func prepare() {
        itemSize = UIScreen.main.bounds.size
        
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        
        scrollDirection = .horizontal
        collectionView?.isPagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
    }
}
